package com.handinglian.employee.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.handinglian.common.dto.ResultData;
import com.handinglian.common.enums.ValidEnum;
import com.handinglian.common.exception.BizException;
import com.handinglian.common.factory.ResultDataFactory;
import com.handinglian.common.utils.FastJsonUtil;
import com.handinglian.common.utils.GeneralUtil;
import com.handinglian.common.utils.MD5Util;
import com.handinglian.common.utils.StringUtil;
import com.handinglian.employee.dto.*;
import com.handinglian.employee.entity.*;
import com.handinglian.employee.mapper.UserInfoMapper;
import com.handinglian.employee.param.*;
import com.handinglian.employee.service.*;
import com.handinglian.system.dto.MenuPermissionDto;
import com.handinglian.system.entity.Permission;
import com.handinglian.system.entity.Role;
import com.handinglian.system.entity.UserRoleRelation;
import com.handinglian.system.service.RoleService;
import com.handinglian.system.service.UserRoleRelationService;
import com.handinglian.task.service.TaskUserRelationService;
import com.handinglian.thirdparty.JiGuangAPiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Slf4j
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ExtensionService extensionService;
    @Autowired
    private UserRoleRelationService userRoleRelationService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserTagService userTagService;
    @Autowired
    @Lazy
    private TaskUserRelationService taskUserRelationService;
    @Autowired
    private JiGuangAPiService jiGuangAPiService;


    @Value("${extension.ip}")
    private String extensionIp;
    @Value("${extension.port}")
    private String extensionPort;
    @Value("${file.download.location}")
    private String fileDownloadLocation;

    @Override
    @Transactional
    public ResultData createUserInfo(UserCreateParam userCreateParam) {
        Extension extension = null;
        if (userCreateParam.getPhonePermission() == 1){
            extension = extensionService.loadExtensionByUserIdIsNull();
            if (Objects.isNull(extension)){
                userCreateParam.setPhonePermission(0);
            }
        }
        //产生盐：工号+随机字串
        String salt = userCreateParam.getJobNum() + new SecureRandomNumberGenerator().nextBytes().toHex();
        String password = generatePassword(salt);
        Date now = new Date();
        UserInfo userInfo = FastJsonUtil.ObjectToObject(userCreateParam, UserInfo.class);
        userInfo.setPassword(password);
        userInfo.setSalt(salt);
        userInfo.setCreateTime(now);
        userInfo.setUpdateTime(now);
        userInfo.setValid(ValidEnum.VALID.getKey());
        int amount = userInfoMapper.insertSelective(userInfo);

        if (Objects.nonNull(extension)){
            extension.setUserId(userInfo.getUserId());
            extensionService.updateExtension(extension);
        }

        //内置roleId=2为普通用户
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(userInfo.getUserId());
        userRoleRelation.setRoleId(2);
        userRoleRelationService.createUserRoleRelation(userRoleRelation);


        UserTag importantCustomer = new UserTag(userInfo.getUserId(), "重要客户", new Date());
        UserTag waitToCall = new UserTag(userInfo.getUserId(), "待联系", new Date());
        List<UserTag> userTags = new ArrayList<>();
        userTags.add(importantCustomer);
        userTags.add(waitToCall);
        userTagService.createBatch(userTags);


        if (userCreateParam.getPhonePermission() == 1&&Objects.isNull(extension)){
            return ResultData.extensionLAck();
        }
        return ResultDataFactory.generateSuccessResultData(null);
    }

    private String generatePassword(String salt) {
        String password = "1han2345ding6lian";
        String passwordMd5 = MD5Util.encrypt(password);

        SimpleHash hash = new SimpleHash("md5", passwordMd5, salt, 2);
        return hash.toHex();
    }

    @Override
    @Transactional
    public int deleteUserInfo(Integer userId) {
        extensionService.updateExtensionByUserId(null, userId);

        taskUserRelationService.updateValid(userId);

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        userInfo.setValid(ValidEnum.INVALID.getKey());
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    public UserInfoDto loadUserInfo(Integer userId) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        return FastJsonUtil.ObjectToObject(userInfo, UserInfoDto.class);
    }

    @Override
    public UserInfo get(Integer userId) {
        return userInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public SystemUserInfoDto loadSystemUserInfo(Integer userId) {
        return userInfoMapper.loadSystemUserInfo(userId);
    }


    @Override
    @Transactional
    public int updateUserInfo(UserUpdateParam userUpdateParam) {
        UserInfo userInfo = FastJsonUtil.ObjectToObject(userUpdateParam, UserInfo.class);
        userInfo.setUpdateTime(new Date());
        int amount = userInfoMapper.updateByPrimaryKeySelective(userInfo);

        if (userUpdateParam.getPhonePermission() == 0){
            extensionService.updateExtensionByUserId(null, userUpdateParam.getUserId());
        } else {
            ExtensionDto extensionDto = extensionService.loadExtensionByUserId(userUpdateParam.getUserId());
            if (extensionDto == null){
                Extension extension = extensionService.loadExtensionByUserIdIsNull();
                if (Objects.isNull(extension)){
                    throw BizException.EXTENSION_LACK;
                }
                extension.setUserId(userUpdateParam.getUserId());
                extensionService.updateExtension(extension);
            }
        }
        return amount;
    }

    @Override
    @Transactional
    public int updateUserInfo(UserInfo userInfo) {
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    @Transactional
    public int updateSystemUser(SystemUserParam systemUserParam) {
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(systemUserParam.getUserId());
        userRoleRelation.setRoleId(systemUserParam.getRoleId());
        userRoleRelationService.updateUserRoleRelation(userRoleRelation);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(systemUserParam.getUserId());
        userInfo.setDataList(systemUserParam.getDataPermissionList());
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    @Transactional
    public int createSystemUser(SystemUserParam systemUserParam) {
        userRoleRelationService.deleteUserRoleRelation(systemUserParam.getUserId());

        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(systemUserParam.getUserId());
        userRoleRelation.setRoleId(systemUserParam.getRoleId());
        userRoleRelationService.createUserRoleRelation(userRoleRelation);

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(systemUserParam.getUserId());
        userInfo.setDataList(systemUserParam.getDataPermissionList());
        return userInfoMapper.updateByPrimaryKey(userInfo);
    }

    @Override
    @Transactional
    public int deleteSystemUser(Integer userId) {
        //内置roleId=2为普通用户
        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(userId);
        userRoleRelation.setRoleId(2);
        userRoleRelationService.updateUserRoleRelation(userRoleRelation);

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        userInfo.setDataList(null);
        return userInfoMapper.updateByPrimaryKey(userInfo);
    }

    @Override
    @Transactional
    public int recoverUserInfo(String jobNum) {
        UserInfo userInfo = userInfoMapper.findInvalidOneByJobNum(jobNum);

        Extension extension = null;
        if (userInfo.getPhonePermission() == 1){
            extension = extensionService.loadExtensionByUserIdIsNull();
            if (extension == null){
                userInfo.setPhonePermission(0);
            }
        }
        userInfo.setValid(ValidEnum.VALID.getKey());
        userInfoMapper.updateByPrimaryKeySelective(userInfo);

        int flag = 1;
        if (extension != null){
            //绑定分机
            extension.setUserId(userInfo.getUserId());
            extensionService.updateExtension(extension);
        } else {
            flag = 0;
        }
        return flag;
    }

    @Override
    public UserInfo loadInvalidUserInfo(String jobNum) {
        return userInfoMapper.findInvalidOneByJobNum(jobNum);
    }

    @Override
    public PageInfo<UserInfoDto> inquireUserInfoPageList(Integer userId, String nameOrJobNumOrPhone, String departmentName, String sexs, String phonePermissions, Integer pageIndex, Integer pageSize) {
        extensionService.refreshExtension();

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        List<Integer> departmentIds = null;
        if (!userInfo.getJobNum().equals("admin")){
            String dataList = userInfo.getDataList();
            departmentIds = StringUtil.stringToIntegerList(dataList);
        }
        List<Integer> sexList = StringUtil.stringToIntegerList(sexs);
        List<Integer> permissionList = StringUtil.stringToIntegerList(phonePermissions);
        pageIndex = pageIndex == null ? 1 : pageIndex;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageIndex, pageSize);
        List<UserInfoDto> userInfoList = userInfoMapper.inquireUserInfoPageList(nameOrJobNumOrPhone, departmentName, sexList, permissionList, departmentIds);

        return new PageInfo(userInfoList);
    }

    @Override
    public PageInfo<SystemUserInfoDto> inquireSystemUserInfoPageList(Integer userId, String nameOrJobNumOrPhone, String loginStates, Integer pageIndex, Integer pageSize) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        List<Integer> departmentIds = null;
        if (!userInfo.getJobNum().equals("admin")){
            String dataList = userInfo.getDataList();
            departmentIds = StringUtil.stringToIntegerList(dataList);
        }
        List<Integer> loginStateList = StringUtil.stringToIntegerList(loginStates);

        pageIndex = pageIndex == null ? 1 : pageIndex;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageIndex, pageSize);
        List<SystemUserInfoDto> systemUserInfoDtos = userInfoMapper.inquireSystemUserInfoPageList(departmentIds, nameOrJobNumOrPhone, loginStateList);
        return new PageInfo(systemUserInfoDtos);
    }

    @Override
    public List<String> inquireUserInfoByJobNum(List<String> jobNumList) {
        return userInfoMapper.findJobNumByJobNumIn(jobNumList);
    }

    @Override
    public ImportUserDto importUserTemplateExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response, MultipartFile file, Integer flag) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<UserTemplateExcel> userTemplateExcels = ExcelImportUtil.importExcel(file.getInputStream(),UserTemplateExcel.class, importParams);
        userTemplateExcels = userTemplateExcels.stream().filter(userTemplateExcel -> StrUtil.isNotBlank(userTemplateExcel.getJobNum())).collect(Collectors.toList());
        userTemplateExcels.forEach(userTemplateExcel -> {
            String phonePermission = userTemplateExcel.getPhonePermission().equals("开")?"1":"0";
            userTemplateExcel.setPhonePermission(phonePermission);
        });

        List<String> jobNums = userTemplateExcels.stream().map(userTemplateExcel -> userTemplateExcel.getJobNum()).collect(Collectors.toList());
        //查询数据库中已存在的工号
        List<String> jobNumDB = inquireUserInfoByJobNum(jobNums);

        int count = 0;
        int countUserIdIsNull = extensionService.countByExtensionUserIdIsNull();
        for (int i = 0;i < userTemplateExcels.size();i++){
            StringBuffer stringBuffer = new StringBuffer();
            UserTemplateExcel userTemplateExcel = userTemplateExcels.get(i);
            if (jobNumDB.contains(userTemplateExcel.getJobNum())){
                stringBuffer.append("该工号已存在;");
                count++;
            }
            if (i > countUserIdIsNull -1){
                stringBuffer.append("分机号不足;");
                userTemplateExcel.setPhonePermission("0");
            }
            userTemplateExcel.setErrorInfo(stringBuffer.toString());
        }

        int insertCount = 0;
        flag = flag == null?0:flag;
        if (flag == 1){
            //将数据库中已存在的工号排除
            List<UserTemplateExcel> userTemplateExcelList = userTemplateExcels.stream().filter(userTemplateExcel -> !jobNumDB.contains(userTemplateExcel.getJobNum())).collect(Collectors.toList());
            if (userTemplateExcelList.size() > 0){
                insertCount = batchCreateUser(userTemplateExcelList);
            }
        } else {
            if (count == 0){
                insertCount = batchCreateUser(userTemplateExcels);
            }
        }

        //返回数据
        ImportUserDto importUserDto = new ImportUserDto();
        importUserDto.setSuccessNumber(insertCount);
        importUserDto.setFailureNumber(count);
        userTemplateExcels = userTemplateExcels.stream().filter(userTemplateExcel -> StrUtil.isNotBlank(userTemplateExcel.getErrorInfo())).collect(Collectors.toList());
        importUserDto.setUserTemplateExcels(userTemplateExcels);
        return importUserDto;
    }

    private int batchCreateUser(List<UserTemplateExcel> userTemplateExcels) {
        List<String> departmentNames = userTemplateExcels.stream().map(userTemplateExcel -> userTemplateExcel.getDepartmentName()) .collect(Collectors.toList());
        List<Department> departments = departmentService.inquireDepartmentByDepartmentName(departmentNames);

        for (UserTemplateExcel userTemplateExcel : userTemplateExcels){
            for (Department department : departments){
                if (userTemplateExcel.getDepartmentName().equals(department.getDepartmentName())){
                    userTemplateExcel.setDepartmentId(department.getDepartmentId());
                    break;
                }
            }
        }

        List<UserInfo> userInfos = FastJsonUtil.ListToList(userTemplateExcels, UserInfo.class);
        Date now = new Date();
        userInfos.forEach(userInfo -> {
            String sex = userInfo.getSex();
            sex = "男".equals(sex)?"1":("女".equals(sex)?"2":"3");
            userInfo.setSex(sex);
            userInfo.setValid(ValidEnum.VALID.getKey());

            String salt = userInfo.getJobNum() + new SecureRandomNumberGenerator().nextBytes().toHex();
            userInfo.setSalt(salt);
            String password = generatePassword(salt);
            userInfo.setPassword(password);

            userInfo.setCreateTime(now);
            userInfo.setUpdateTime(now);
        });
        int amount = userInfoMapper.batchInsert(userInfos);

        List<UserRoleRelation> userRoleRelations = new ArrayList<>();
        userInfos.forEach(userInfo -> {
            UserRoleRelation userRoleRelation = new UserRoleRelation();
            userRoleRelation.setUserId(userInfo.getUserId());
            userRoleRelation.setRoleId(2);
            userRoleRelations.add(userRoleRelation);
        });
        userRoleRelationService.batchInsert(userRoleRelations);

        List<UserTag> userTags = new ArrayList<>();
        userInfos.forEach(userInfo -> {
            UserTag importantCustomer = new UserTag(userInfo.getUserId(), "重要客户", new Date());
            UserTag waitToCall = new UserTag(userInfo.getUserId(), "待联系", new Date());
            userTags.add(importantCustomer);
            userTags.add(waitToCall);
        });
        userTagService.createBatch(userTags);


        //设置用户的电话权限
        List<UserInfo> phonePermissionUsers = userInfos.stream().filter(userInfo -> userInfo.getPhonePermission().equals(1)).collect(Collectors.toList());
        for (UserInfo userInfo : phonePermissionUsers){
            int updateAmount = extensionService.updateUserIdByUserIdIsNull(userInfo.getUserId());
            if (updateAmount == 0){
                break;
            }
        }
        return amount;
    }

    @Override
    public List<Permission> inquirePermissionList(String jobNum) {
        return userInfoMapper.inquirePermissionList(jobNum);
    }

    @Override
    public UserInfoDetailDto loadUserDetailByJobNum(String jobNum) {
        UserInfoDetailDto detailDto = userInfoMapper.loadUserDetailByJobNum(jobNum);
        Role role = roleService.getByUserId(detailDto.getUserId());
        if (role != null){
            detailDto.setRoleId(role.getRoleId());
            detailDto.setRoleName(role.getRoleName());

            List<MenuPermissionDto> menuPermissionDtos = roleService.getRoleMenuPermissionList(role.getRoleId());
            menuPermissionDtos.forEach(menuPermissionDto -> {
                List<String> permissionIdList = StrUtil.split(menuPermissionDto.getPermissionIds(),',');
                menuPermissionDto.setPermissionIdList(permissionIdList);
            });
            detailDto.setMenuPermissionDtos(menuPermissionDtos);
        }

        return detailDto;
    }

    @Override
    public UserInfo loadUserByJobNum(String jobNum) {
        return userInfoMapper.findOneByJobNum(jobNum);
    }

    @Override
    public ExtensionDto loadExtensionByJobNum(String jobNum) {
        UserInfo userInfo = userInfoMapper.findOneByJobNum(jobNum);
        ExtensionDto extensionDto = extensionService.loadExtensionByUserId(userInfo.getUserId());
        if (extensionDto != null){
            extensionDto.setIp(extensionIp);
            extensionDto.setPort(extensionPort);
        }
        return extensionDto;
    }

    @Override
    public List<UserInfoDto> inquireUserInfoByDepartmentId(Integer departmentId, String nameOrPhone) {
        List<UserInfo> userInfos = userInfoMapper.list(departmentId, nameOrPhone);
        List<UserInfoDto> userInfoDtos = FastJsonUtil.ListToList(userInfos, UserInfoDto.class);

        List<String> fileUuids = userInfos.stream().filter(userInfo -> StrUtil.isNotBlank(userInfo.getImageId())).map(userInfo -> userInfo.getImageId()).collect(Collectors.toList());
        List<FileInfo> fileInfos;
        if (fileUuids.size() > 0){
            fileInfos = fileInfoService.inquireFileInfoList(fileUuids);
            for (UserInfoDto userInfoDto : userInfoDtos){
                for (FileInfo fileInfo : fileInfos){
                    if (StringUtil.isNotBlank(userInfoDto.getImageId())&&userInfoDto.getImageId().equals(fileInfo.getFileUuid())){
                        userInfoDto.setImagePath(fileInfo.getFilePath());
                    }
                }
            }
        }


        return userInfoDtos;
    }

    @Override
    public List<UserInfo> listSubByDepartmentId(Integer departmentId) {
        List<Department> departments = departmentService.listSubDepartmentId(departmentId);
        List<Integer> departmentIds = departments.stream().map(department -> department.getDepartmentId()).collect(Collectors.toList());
        return userInfoMapper.findByDepartmentIdIn(departmentIds);
    }

    @Override
    @Transactional
    public int updatePassword(UpdatePasswordParam updatePasswordParam) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(updatePasswordParam.getUserId());
        String parmaPassword = new SimpleHash("md5", updatePasswordParam.getOldPassword(), userInfo.getSalt(), 2).toHex();
        //确认原密码与数据库中的密码是否一致
        if (!parmaPassword.equals(userInfo.getPassword())){
            throw BizException.OLD_PASSWORD_ERROR;
        }

        String dbPassword = new SimpleHash("md5", updatePasswordParam.getNewPassword(), userInfo.getSalt(), 2).toHex();
        userInfo.setPassword(dbPassword);
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    @Transactional
    public String uploadHeadImage(MultipartFile file, Integer userId) {
        FileInfo fileInfo = new FileInfo();

        String uuid = GeneralUtil.randomUUID();
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = uuid + suffixName;

        fileInfo.setFileUuid(uuid);
        fileInfo.setFileName(file.getOriginalFilename());
        fileInfo.setFileSize(String.valueOf(file.getSize()));
        fileInfo.setFilePath("/"+fileName);
        fileInfo.setCreateTime(new Date());
        fileInfoService.createFile(fileInfo);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setImageId(fileInfo.getFileUuid());
        int amount = userInfoMapper.updateByPrimaryKeySelective(userInfo);

        uploadImage(file, fileName);
        return "/"+fileName;
    }

    @Override
    public void downloadHeadImage(HttpServletResponse response, String fileUuid) {
        FileInfo fileInfo = fileInfoService.loadFile(fileUuid);
        String filePath = fileInfo.getFilePath();

        String imageName = fileInfo.getFileName();
        if (StringUtil.isNotBlank(filePath)) {
            File file = new File(filePath);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + imageName);// 设置文件名
                byte[] buffer = new byte[1024];
                try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    log.error("流输入输出异常",e);
                    throw BizException.STREAM_ERROR;
                }
            }
        }
    }


    private void uploadImage(MultipartFile file, String fileName){
        if (file.isEmpty()) {
            throw BizException.FILE_IS_NULL;
        }

        String filePath = fileDownloadLocation;
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            log.error("文件上传失败",e);
            throw BizException.FILE_TRANSFER_FAILURE;
        }
    }

    @Override
    public List<UserInfo> inquireUserIdByJobNum(Collection<String> jobNumCollection) {
        return userInfoMapper.findByJobNumIn(jobNumCollection);
    }

    @Override
    @Transactional
    public int resetPassword(Integer userId) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        //产生盐：工号+随机字串
        String salt = userInfo.getSalt();
        String password = generatePassword(salt);
        userInfo.setPassword(password);
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    @Transactional
    public int updateLoginState(LoginStateUpdateParam loginStateParam) {
        UserInfo userInfo = FastJsonUtil.ObjectToObject(loginStateParam, UserInfo.class);
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    @Async
    public Future<Integer> count() {
        return new AsyncResult<>(userInfoMapper.count());
    }

    @Override
    @Async
    public Future<Integer> countSystemUser() {
        return new AsyncResult<>(userInfoMapper.countByDataListIsNotNull());
    }

    @Override
    public List<UserInfo> list(List<Integer> departmentIds) {
        return userInfoMapper.findByDepartmentIdIn(departmentIds);
    }

    @Override
    public List<String> findPushIdByJobNum(String jobNum) {
        return userInfoMapper.findPushIdByJobNum(jobNum);
    }

    @Override
    @Transactional
    public int updatePushIdByJobNum(String updatedPushId, String jobNum) {
        return userInfoMapper.updatePushIdByJobNum(updatedPushId, jobNum);
    }

    @Override
    public UserInfo get(String jobNum, String pushId) {
        return userInfoMapper.findOneByJobNumAndPushId(jobNum, pushId);
    }

    @Override
    public List<UserInfoDto> list() {
        return userInfoMapper.listUserInfoDto();
    }

    @Override
    @Transactional
    public void pushAll() throws IOException {
        List<String> pushIds = userInfoMapper.findPushIdByPushIdIsNotNull();
        List<String> pushIdRight = new ArrayList<>();
        for (String pushId : pushIds){
            String response = jiGuangAPiService.singleLoginPushTest(pushId);
            if (response.indexOf("error") == -1){
                pushIdRight.add(pushId);
            }
        }
        userInfoMapper.updatePushIdByPushIdIn(pushIdRight);
        System.out.println(pushIdRight);
    }
}
